package com.graduation.lastproject.util.shiro;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.shiro.authz.ModularRealmAuthorizer;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoginsModularRealmAuthorizer extends ModularRealmAuthorizer {
    private static Logger logger=LoggerFactory.getLogger(LoginsModularRealmAuthenticator.class);
    @Override
    public boolean hasRole(PrincipalCollection principals, String roleIdentifier) {
        logger.info("好起来了呀---realm授权：");
        assertRealmsConfigured();
        // 所有Realm
        Collection<Realm> realms = getRealms();
        HashMap<String, Realm> realmHashMap = new HashMap<>(realms.size());
        for (Realm realm : realms) {
            if (realm.getName().contains("Admin")) {
                realmHashMap.put("AdminRealm", realm);
            }
            if (realm.getName().contains("User")) {
                realmHashMap.put("UserRealm", realm);
            }
        }
        Set<String> realmNames = principals.getRealmNames();
        if (realmNames != null) {
            String realmName = null;
            Iterator it = realmNames.iterator();
            while (it.hasNext()) {
                realmName = ConvertUtils.convert(it.next());
                if (realmName.contains("admin")) {
                    return ((AdminRealm) realmHashMap.get("AdminRealm")).hasRole(principals,roleIdentifier);
                }
                if (realmName.contains("user")) {
                    return ((UserRealm) realmHashMap.get("UserRealm")).hasRole(principals,roleIdentifier);
                }
                break;
            }
        }
        return false;
    }
}
